package com.hydl.power.service.impl;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hydl.power.mapper.*;
import com.hydl.power.pojo.*;
import com.hydl.power.service.MqttDataService;
import com.hydl.power.utils.*;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import lombok.extern.log4j.Log4j2;

@Service
@Log4j2
public class MqttDataServiceImpl implements MqttDataService {

    /**
     * 电表数据 上一次保存到数据库的时间
     */
    private long powerDataLastSavedMillis = System.currentTimeMillis();
    /**
     * 温控数据 上一次保存到数据库的时间
     */
    private long tempDataLastSavedMillis = System.currentTimeMillis();
    /**
     * 综保数据 上一次保存到数据库的时间
     */
    private long protectDataLastSavedMillis = System.currentTimeMillis();
    /**
     * 保存间隔时间,单位毫秒
     *
     * 默认10分钟
     */
    private static final long SAVE_INTERVAL_MILLIS = 10 * 60 * 1000;
    // private static final long SAVE_INTERVAL_MILLIS = 10 * 1000;

    @Autowired
    private PowerdataMapper powerdataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private MaintainerMapper maintainerMapper;

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private IncomingCabinetMapper incomingCabinetMapper;

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private TemperatureDataMapper temperatureMapper;

    @Autowired
    private PushMapper pushMapper;

    @Autowired
    private TemperatureDeviceMapper temperatureDeviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MarketingMapper marketingMapper;

    @Autowired
    private GatewayMapper gatewayMapper;
    @Autowired
    private ProtectDeviceMapper protectDeviceMapper;
    @Autowired
    private ProtectDataMapper protectDataMapper;
    @Autowired
    private PowerDeviceMapper powerDeviceMapper;
    @Autowired
    private PowerDataNewMapper powerDataNewMapper;
    @Autowired
    private TempDataMapper tempDataMapper;
    @Autowired
    private TempDeviceMapper tempDeviceMapper;

    @Override
    public int save(String message) {
        log.info("MqttDataServiceImpl save start:\n{}", message);
        // 是否保存到数据库判断
        // long currentTimeMillis = System.currentTimeMillis();
        // long interval = currentTimeMillis - lastSavedMillis;
        // if (interval < SAVE_INTERVAL_MILLIS) {
        //     log.info("未到保存时间,currentTimeMillis:{},lastSavedMillis:{},interval:{}", currentTimeMillis, lastSavedMillis, interval);
        //     return -1;
        // }
        //todo 位置
        // lastSavedMillis = currentTimeMillis;
        JSONObject msgObject = JSONObject.parseObject(message);
        String groupName = msgObject.getString("_groupName");
        if (StringUtils.isBlank(groupName)) {
            log.error("groupName is null");
            return -1;
        }
        // groupName = device_id
        String[] groupNameStr = StringUtils.split(groupName, "_");
        //网关自定义编号 gateway_sn
        String gatawaySn = groupNameStr[0];
        //设备类型 1 综保 2 电表 3，温控
        String deviceType = groupNameStr[1];
        log.info("开始保存,gatawaySn:{},deviceType:{}", gatawaySn, deviceType);
        // 设备地址 （485地址）
        String deviceAddress = groupNameStr[2];
        //网关编号
        List<String> gateWaySnList = gatewayMapper.selectGateWaySn();
        if (gateWaySnList.contains(gatawaySn)) {
            //根据 设备类型 插入对比表
            if ("1".equals(deviceType)) {
                // ProtectDevice protectDevice = new ProtectDevice();
                // protectDevice.setDeviceId(groupName);
                // protectDevice.setDeviceType(Integer.parseInt(deviceType));
                // protectDevice.setDeviceName("综保");
                // protectDevice.setGatewaySn(gatawaySn);
                // protectDevice.setGatewayName("郑源电气配电网关");
                // protectDeviceMapper.insert(protectDevice);
                ProtectData protectData = new ProtectData();
                protectData.setDeviceId(groupName);
                protectData.setDeviceName(groupName);
                protectData.setIa(msgObject.getString("Modbus_8_Ia"));
                protectData.setIb(msgObject.getString("Modbus_8_Ib"));
                protectData.setIc(msgObject.getString("Modbus_8_Ic"));
                protectData.setUa(msgObject.getString("Modbus_8_Ua"));
                protectData.setUb(msgObject.getString("Modbus_8_Ub"));
                protectData.setUc(msgObject.getString("Modbus_8_Uc"));
                protectData.setP(msgObject.getString("Modbus_8_P"));
                protectData.setQ(msgObject.getString("Modbus_8_Q"));
                protectData.setF(msgObject.getString("Modbus_8_F"));
                protectData.setI0(msgObject.getString("Modbus_8_I0"));
                protectData.setU0(msgObject.getString("Modbus_8_U0"));
                protectData.setCos(msgObject.getString("Modbus_8_cos"));
                protectData.setUab(msgObject.getString("Modbus_8_Uab"));
                protectData.setUbc(msgObject.getString("Modbus_8_Ubc"));
                protectData.setUca(msgObject.getString("Modbus_8_Uca"));
                protectData.setCircuitBreakerSwitchOnPosition(msgObject.getString("Modbus_8_断路器合位置"));
                protectData.setCircuitBreakerTripPosition(msgObject.getString("Modbus_8_断路器跳位置"));
                protectData.setRemoteLocation(msgObject.getString("Modbus_8_远方位置"));
                protectData.setSpringNotStoreEnergy(msgObject.getString("Modbus_8_弹簧未储能弹簧未储能"));
                protectData.setLightGasSignal(msgObject.getString("Modbus_8_轻瓦斯信号"));
                protectData.setHighTemperatureSignal(msgObject.getString("Modbus_8_温度高信号"));
                protectData.setHeavyGasSignal(msgObject.getString("Modbus_8_重瓦斯信号"));
                protectData.setOvertemperatureTripSignal(msgObject.getString("Modbus_8_超温跳闸信号"));
                protectData.setGroundingSwitchSignal(msgObject.getString("Modbus_8_接地刀闸信号"));
                protectData.setTemperatureControllerFault(msgObject.getString("Modbus_8_温控器故障"));
                protectData.setInput1(msgObject.getString("Modbus_8_开入1"));
                protectData.setInput2(msgObject.getString("Modbus_8_开入2"));
                protectData.setVar12(msgObject.getString("Modbus_8_变量12"));
                protectData.setVar13(msgObject.getString("Modbus_8_变量13"));
                protectData.setVar14(msgObject.getString("Modbus_8_变量14"));
                protectData.setVar15(msgObject.getString("Modbus_8_变量15"));
                protectData.setQuickBreakActionEventSign(msgObject.getString("Modbus_8_速断动作事件标志"));
                protectData.setOvercurrent1(msgObject.getString("Modbus_8_过流1"));
                protectData.setOvercurrent2(msgObject.getString("Modbus_8_过流2"));
                protectData.setInverseTimeOverload(msgObject.getString("Modbus_8_反时限过负荷"));
                protectData.setHvSideZeroSeqOvercurrent(msgObject.getString("Modbus_8_高压侧零序过流"));
                protectData.setLvSideInverseTimeZeroSeqOvercurrent(msgObject.getString("Modbus_8_低压侧反时限零序过流"));
                protectData.setNoumenonTrip(msgObject.getString("Modbus_8_本体跳闸"));
                protectData.setControlFault(msgObject.getString("Modbus_8_控故障"));
                protectData.setPtDisconnection(msgObject.getString("Modbus_8_PT断线"));
                protectData.setInverseTimeOverloadWarning(msgObject.getString("Modbus_8_反时限过负荷预警"));
                protectData.setReserved(msgObject.getString("Modbus_8_保留"));
                protectData.setInverseTimeOverloadAlarm(msgObject.getString("Modbus_8_反时限过负荷告警"));
                protectData.setOvervoltageProtection(msgObject.getString("Modbus_8_过压保护"));
                protectData.setVoltageLossProtection(msgObject.getString("Modbus_8_失压保护"));
                protectData.setVar30(msgObject.getString("Modbus_8_变量30"));
                protectData.setVar31(msgObject.getString("Modbus_8_变量31"));
                protectData.setRemoteSwitchOn(msgObject.getString("Modbus_8_遥控合"));
                protectData.setRemoteSwitchOff(msgObject.getString("Modbus_8_遥控分"));
                protectData.setLocalSwitchOn(msgObject.getString("Modbus_8_就地合"));
                protectData.setLocalSwitchOff(msgObject.getString("Modbus_8_就地分"));
                protectData.setHvSideZeroSeqOvercurrentAlarm(msgObject.getString("Modbus_8_高压侧零序过流告警"));
                protectData.setLvSideZeroSeqOvercurrentAlarm(msgObject.getString("Modbus_8_低压侧零序过流告警"));
                protectData.setVar38(msgObject.getString("Modbus_8_变量38"));
                protectData.setVar39(msgObject.getString("Modbus_8_变量39"));
                protectData.setVar40(msgObject.getString("Modbus_8_变量40"));
                protectData.setVar41(msgObject.getString("Modbus_8_变量41"));
                protectData.setVar42(msgObject.getString("Modbus_8_变量42"));
                protectData.setVar43(msgObject.getString("Modbus_8_变量43"));
                protectData.setVar44(msgObject.getString("Modbus_8_变量44"));
                protectData.setVar45(msgObject.getString("Modbus_8_变量45"));
                protectData.setAlarmTotalSignal(msgObject.getString("Modbus_8_告警总信号"));
                protectData.setAccidentTotalSignal(msgObject.getString("Modbus_8_事故总信号"));
                protectData.setCreatetime(new Date());
                redisTemplate.opsForValue()
                    .set(groupName, JSON.toJSONString(protectData));
                if (saveProtectData()) {
                    protectDataMapper.insert(protectData);
                }
            } else if ("2".equals(deviceType)) {
                PowerDataNew powerDataNew = new PowerDataNew();
                powerDataNew.setDeviceId(groupName);
                powerDataNew.setIemi("");
                powerDataNew.setIa(msgObject.getString("Modbus_2_Ia"));
                powerDataNew.setIb(msgObject.getString("Modbus_2_Ib"));
                powerDataNew.setIc(msgObject.getString("Modbus_2_Ic"));
                powerDataNew.setUa("");
                powerDataNew.setUb("");
                powerDataNew.setUc("");
                powerDataNew.setUab(msgObject.getString("Modbus_2_Uab"));
                powerDataNew.setUbc(msgObject.getString("Modbus_2_Ubc"));
                powerDataNew.setUca(msgObject.getString("Modbus_2_Uca"));
                powerDataNew.setPa("");
                powerDataNew.setPb("");
                powerDataNew.setPc("");
                powerDataNew.setPt("");
                powerDataNew.setPan("");
                powerDataNew.setPbn("");
                powerDataNew.setPcn("");
                powerDataNew.setPtn("");
                powerDataNew.setPaf("");
                powerDataNew.setPbf("");
                powerDataNew.setPcf("");
                powerDataNew.setPtf("");
                powerDataNew.setPain("");
                powerDataNew.setPbin("");
                powerDataNew.setPcin("");
                powerDataNew.setPtin("");
                powerDataNew.setFrequency("");
                powerDataNew.setCreatetime(new Date());
                powerDataNew.setCombinedactivetipenergy("");
                powerDataNew.setForwardactivetotalelectricalenergy("");
                powerDataNew.setTotalreverseactiveenergy("");
                powerDataNew.setWpp("");
                powerDataNew.setEpp("");
                powerDataNew.setMwpp("");
                powerDataNew.setDeviceName(groupName);
                redisTemplate.opsForValue()
                    .set(groupName, JSON.toJSONString(powerDataNew));
                if (savePowerData()) {
                    powerDataNewMapper.insert(powerDataNew);
                }
                // PowerDevice powerDevice = new PowerDevice();
                // powerDevice.setDeviceId(groupName);
                // powerDevice.setDeviceName("电表");
                // powerDevice.setDeviceAddress(deviceAddress);
                // powerDevice.setDeviceType(Integer.parseInt(deviceType));
                // powerDevice.setGatewaySn(gatawaySn);
                // powerDeviceMapper.insert(powerDevice);
            } else if ("3".equals(deviceType)) {
                // TempDevice tempDevice = new TempDevice();
                // tempDevice.setDeviceId(groupName);
                // tempDevice.setDeviceType();
                Integer projectId = null;
                Integer powerRoomId = null;
                TempDeviceExample example = new TempDeviceExample();
                TempDeviceExample.Criteria criteria = example.createCriteria();
                criteria.andDeviceIdEqualTo(groupName);
                List<TempDevice> tempDeviceList = tempDeviceMapper.selectByExample(example);
                if (CollectionUtils.isNotEmpty(tempDeviceList)) {
                    projectId = tempDeviceList.get(0).getProjectId();
                    powerRoomId = tempDeviceList.get(0).getPowerroomId();
                }

                TempData tempData = new TempData();
                tempData.setDeviceId(groupName);
                tempData.setDeviceName(groupName);
                tempData.setAreaId("");
                tempData.setProjectId(projectId+"");
                tempData.setPowerRoomId(powerRoomId+"");
                tempData.setTemperatureA(msgObject.getString("Modbus_3_A相温度"));
                tempData.setTemperatureB(msgObject.getString("Modbus_3_B相温度"));
                tempData.setTemperatureC(msgObject.getString("Modbus_3_C相温度"));
                tempData.setTemperatureN(msgObject.getString("Modbus_3_D相温度"));
                tempData.setCreateTime(new Date());
                redisTemplate.opsForValue()
                    .set(groupName, JSON.toJSONString(tempData));
                if (saveTempData()) {
                    tempDataMapper.insert(tempData);
                }
            } else {

            }
        } else {
            log.info("网关编号[{}]在gateway中不存在", gatawaySn);
        }

        return 0;
    }

    private boolean saveTempData() {
        boolean flag = false;
        long currentTimeMillis = System.currentTimeMillis();
        long interval = currentTimeMillis - tempDataLastSavedMillis;
        if (interval < SAVE_INTERVAL_MILLIS) {
            log.info("未到保存时间,currentTimeMillis:{},tempDataLastSavedMillis:{},interval:{}", currentTimeMillis, tempDataLastSavedMillis, interval);
        }else {
            log.info("已到保存时间,currentTimeMillis:{},tempDataLastSavedMillis:{},interval:{}", currentTimeMillis, tempDataLastSavedMillis, interval);
            flag = true;
            tempDataLastSavedMillis = currentTimeMillis;
        }
        return flag;
    }

    private boolean savePowerData() {
        boolean flag = false;
        long currentTimeMillis = System.currentTimeMillis();
        long interval = currentTimeMillis - powerDataLastSavedMillis;
        if (interval < SAVE_INTERVAL_MILLIS) {
            log.info("未到保存时间,currentTimeMillis:{},powerDataLastSavedMillis:{},interval:{}", currentTimeMillis, powerDataLastSavedMillis, interval);
        }else {
            log.info("已到保存时间,currentTimeMillis:{},powerDataLastSavedMillis:{},interval:{}", currentTimeMillis, powerDataLastSavedMillis, interval);
            flag = true;
            powerDataLastSavedMillis = currentTimeMillis;
        }
        return flag;
    }
    private boolean saveProtectData() {
        boolean flag = false;
        long currentTimeMillis = System.currentTimeMillis();
        long interval = currentTimeMillis - protectDataLastSavedMillis;
        if (interval < SAVE_INTERVAL_MILLIS) {
            log.info("未到保存时间,currentTimeMillis:{},protectDataLastSavedMillis:{},interval:{}", currentTimeMillis, protectDataLastSavedMillis, interval);
        }else {
            log.info("已到保存时间,currentTimeMillis:{},protectDataLastSavedMillis:{},interval:{}", currentTimeMillis, protectDataLastSavedMillis, interval);
            flag = true;
            protectDataLastSavedMillis = currentTimeMillis;
        }
        return flag;
    }
    // 是否保存到数据库判断
    // long currentTimeMillis = System.currentTimeMillis();
    // long interval = currentTimeMillis - lastSavedMillis;
    // if (interval < SAVE_INTERVAL_MILLIS) {
    //     log.info("未到保存时间,currentTimeMillis:{},lastSavedMillis:{},interval:{}", currentTimeMillis, lastSavedMillis, interval);
    //     return -1;
    // }
    //todo 位置
    // lastSavedMillis = currentTimeMillis;
    /*@Override
    public int save(String message) {
        if (!message.equals("close")) {
            JSONObject jsonObject = JSONObject.parseObject(message);
            String type = jsonObject.getString("type");
            if (type.equals("real")) {
                String data = jsonObject.getString("data");
                JSONObject dataJson = JSONObject.parseObject(data);
                String key = "";
                Date time = jsonObject.getDate("time");
                int minutes=  time.getMinutes();
                int seconds = time.getSeconds();
                if(minutes%10==0){
                    if(seconds>10 && seconds<23){
                        for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
                            key = entry.getKey();
                            Device deviceByDeviceName=null;
                            if(key.substring(0,2).equals("通道")){
                                int i = key.indexOf("_");
                                if(i!= -1){
                                    String str = key.substring(i + 1);
                                    deviceByDeviceName = deviceMapper.getAllDeviceByDeviceName(str);
                                }
                            }else{
                                deviceByDeviceName = deviceMapper.getAllDeviceByDeviceName(key);
                            }
                            if(deviceByDeviceName!=null){
                                String jsonStr = dataJson.getString(key);
                                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                                if (jsonArray != null) {
                                    if(jsonArray.size()==32){
                                        if(jsonArray.getJSONObject(26).getFloat("quality")==1){
                                            Powerdata powerdata = new Powerdata();
                                            powerdata.setDeviceid(deviceByDeviceName.getSerialNumber());
                                            powerdata.setCreatetime(time);
                                            powerdata.setDeviceName(deviceByDeviceName.getDeviceName());
                                            powerdata.setUa(jsonArray.getJSONObject(0).getFloat("value"));
                                            powerdata.setUb(jsonArray.getJSONObject(1).getFloat("value"));
                                            powerdata.setUc(jsonArray.getJSONObject(2).getFloat("value"));
                                            powerdata.setUab(jsonArray.getJSONObject(3).getFloat("value"));
                                            powerdata.setUbc(jsonArray.getJSONObject(4).getFloat("value"));
                                            powerdata.setUca(jsonArray.getJSONObject(5).getFloat("value"));
                                            powerdata.setIa(jsonArray.getJSONObject(6).getFloat("value"));
                                            powerdata.setIb(jsonArray.getJSONObject(7).getFloat("value"));
                                            powerdata.setIc(jsonArray.getJSONObject(8).getFloat("value"));
                                            powerdata.setPa(jsonArray.getJSONObject(9).getFloat("value"));
                                            powerdata.setPb(jsonArray.getJSONObject(10).getFloat("value"));
                                            powerdata.setPc(jsonArray.getJSONObject(11).getFloat("value"));
                                            powerdata.setPt(jsonArray.getJSONObject(12).getFloat("value"));
                                            powerdata.setPan(jsonArray.getJSONObject(13).getFloat("value"));
                                            powerdata.setPbn(jsonArray.getJSONObject(14).getFloat("value"));
                                            powerdata.setPcn(jsonArray.getJSONObject(15).getFloat("value"));
                                            powerdata.setPtn(jsonArray.getJSONObject(16).getFloat("value"));
                                            powerdata.setPain(jsonArray.getJSONObject(17).getFloat("value"));
                                            powerdata.setPbin(jsonArray.getJSONObject(18).getFloat("value"));
                                            powerdata.setPcin(jsonArray.getJSONObject(19).getFloat("value"));
                                            powerdata.setPtin(jsonArray.getJSONObject(20).getFloat("value"));
                                            powerdata.setPaf(jsonArray.getJSONObject(21).getFloat("value"));
                                            powerdata.setPbf(jsonArray.getJSONObject(22).getFloat("value"));
                                            powerdata.setPcf(jsonArray.getJSONObject(23).getFloat("value"));
                                            powerdata.setPtf(jsonArray.getJSONObject(24).getFloat("value"));
                                            powerdata.setFrequency(jsonArray.getJSONObject(25).getFloat("value"));
                                            powerdata.setWpp(jsonArray.getJSONObject(26).getFloat("value"));
                                            powerdata.setEpp(jsonArray.getJSONObject(27).getFloat("value"));
                                            powerdata.setMwpp(jsonArray.getJSONObject(28).getFloat("value"));
                                            powerdata.setForwardActiveTotalElectricalEnergy(jsonArray.getJSONObject(26).getFloat("value"));
                                            powerdata.setTotalReverseActiveEnergy(jsonArray.getJSONObject(29).getFloat("value"));
                                            powerdata.setTableName(deviceByDeviceName.getTableName());
                                            int res = powerdataMapper.insertSelective(powerdata);
                                            //添加进线柜实时数据
                                            if (deviceByDeviceName.getTransformerStatus()==1){
                                                IncomingCabinet incomingCabinet=new IncomingCabinet();
                                                incomingCabinet.setDeviceId(deviceByDeviceName.getDeviceId());
                                                incomingCabinet.setDeviceName(deviceByDeviceName.getDeviceName());
                                                incomingCabinet.setSn(powerdata.getDeviceid());
                                                incomingCabinet.setCreateTime(powerdata.getCreatetime());
                                                incomingCabinet.setForwardActiveTotalElectricalEnergy(powerdata.getForwardActiveTotalElectricalEnergy());
                                                incomingCabinet.setPt(powerdata.getPt());
                                                incomingCabinet.setProjectId(deviceByDeviceName.getProjectId());
                                                incomingCabinet.setPtf(powerdata.getPtf());
                                                incomingCabinet.setPtn(powerdata.getPtn());
                                                incomingCabinet.setIa(powerdata.getIa());
                                                incomingCabinet.setIb(powerdata.getIb());
                                                incomingCabinet.setIc(powerdata.getIc());
                                                incomingCabinet.setUa(powerdata.getUa());
                                                incomingCabinet.setUb(powerdata.getUb());
                                                incomingCabinet.setUc(powerdata.getUc());
                                                incomingCabinet.setPtin(powerdata.getPtin());
                                                incomingCabinet.setPa(powerdata.getPa());
                                                incomingCabinet.setPb(powerdata.getPb());
                                                incomingCabinet.setPc(powerdata.getPc());
                                                incomingCabinet.setProjectName(deviceByDeviceName.getNavId());
                                                incomingCabinet.setPowerRoomId(deviceByDeviceName.getPowerRoomId());
                                                incomingCabinet.setPowerRoomName(deviceByDeviceName.getPowerRoomName());
                                                incomingCabinet.setAreaId(deviceByDeviceName.getAreaId());
                                                incomingCabinet.setAreaName(deviceByDeviceName.getAreaName());
                                                incomingCabinet.setTotalReverseActiveEnergy(powerdata.getTotalReverseActiveEnergy());
                                                int i=incomingCabinetMapper.addIncomingCabinet(incomingCabinet);
                                            }
                                        }
                                    }

                                    if(jsonArray.size()>=28 &&  jsonArray.size()<32){
                                        if(jsonArray.getJSONObject(26).getFloat("quality")==1){
                                            Powerdata powerdata = new Powerdata();
                                            powerdata.setDeviceid(deviceByDeviceName.getSerialNumber());
                                            powerdata.setCreatetime(time);
                                            powerdata.setDeviceName(deviceByDeviceName.getDeviceName());
                                            powerdata.setUa(jsonArray.getJSONObject(0).getFloat("value"));
                                            powerdata.setUb(jsonArray.getJSONObject(1).getFloat("value"));
                                            powerdata.setUc(jsonArray.getJSONObject(2).getFloat("value"));
                                            powerdata.setUab(jsonArray.getJSONObject(3).getFloat("value"));
                                            powerdata.setUbc(jsonArray.getJSONObject(4).getFloat("value"));
                                            powerdata.setUca(jsonArray.getJSONObject(5).getFloat("value"));
                                            powerdata.setIa(jsonArray.getJSONObject(6).getFloat("value"));
                                            powerdata.setIb(jsonArray.getJSONObject(7).getFloat("value"));
                                            powerdata.setIc(jsonArray.getJSONObject(8).getFloat("value"));
                                            powerdata.setPa(jsonArray.getJSONObject(9).getFloat("value"));
                                            powerdata.setPb(jsonArray.getJSONObject(10).getFloat("value"));
                                            powerdata.setPc(jsonArray.getJSONObject(11).getFloat("value"));
                                            powerdata.setPt(jsonArray.getJSONObject(12).getFloat("value"));
                                            powerdata.setPan(jsonArray.getJSONObject(13).getFloat("value"));
                                            powerdata.setPbn(jsonArray.getJSONObject(14).getFloat("value"));
                                            powerdata.setPcn(jsonArray.getJSONObject(15).getFloat("value"));
                                            powerdata.setPtn(jsonArray.getJSONObject(16).getFloat("value"));
                                            powerdata.setPain(jsonArray.getJSONObject(17).getFloat("value"));
                                            powerdata.setPbin(jsonArray.getJSONObject(18).getFloat("value"));
                                            powerdata.setPcin(jsonArray.getJSONObject(19).getFloat("value"));
                                            powerdata.setPtin(jsonArray.getJSONObject(20).getFloat("value"));
                                            powerdata.setPaf(jsonArray.getJSONObject(21).getFloat("value"));
                                            powerdata.setPbf(jsonArray.getJSONObject(22).getFloat("value"));
                                            powerdata.setPcf(jsonArray.getJSONObject(23).getFloat("value"));
                                            powerdata.setPtf(jsonArray.getJSONObject(24).getFloat("value"));
                                            powerdata.setFrequency(jsonArray.getJSONObject(25).getFloat("value"));
                                            powerdata.setWpp(jsonArray.getJSONObject(26).getFloat("value"));
                                            powerdata.setEpp(jsonArray.getJSONObject(27).getFloat("value"));
                                            powerdata.setMwpp(jsonArray.getJSONObject(28).getFloat("value"));
                                            powerdata.setForwardActiveTotalElectricalEnergy(jsonArray.getJSONObject(26).getFloat("value"));
                                            powerdata.setTableName(deviceByDeviceName.getTableName());
                                            int res = powerdataMapper.insertSelective(powerdata);
                                            //添加进线柜实时数据
                                            if (deviceByDeviceName.getTransformerStatus()==1){
                                                IncomingCabinet incomingCabinet=new IncomingCabinet();
                                                incomingCabinet.setDeviceId(deviceByDeviceName.getDeviceId());
                                                incomingCabinet.setDeviceName(deviceByDeviceName.getDeviceName());
                                                incomingCabinet.setSn(powerdata.getDeviceid());
                                                incomingCabinet.setCreateTime(powerdata.getCreatetime());
                                                incomingCabinet.setForwardActiveTotalElectricalEnergy(powerdata.getForwardActiveTotalElectricalEnergy());
                                                incomingCabinet.setPt(powerdata.getPt());
                                                incomingCabinet.setProjectId(deviceByDeviceName.getProjectId());
                                                incomingCabinet.setPtf(powerdata.getPtf());
                                                incomingCabinet.setPtn(powerdata.getPtn());
                                                incomingCabinet.setIa(powerdata.getIa());
                                                incomingCabinet.setIb(powerdata.getIb());
                                                incomingCabinet.setIc(powerdata.getIc());
                                                incomingCabinet.setUa(powerdata.getUa());
                                                incomingCabinet.setUb(powerdata.getUb());
                                                incomingCabinet.setUc(powerdata.getUc());
                                                incomingCabinet.setPtin(powerdata.getPtin());
                                                incomingCabinet.setPa(powerdata.getPa());
                                                incomingCabinet.setPb(powerdata.getPb());
                                                incomingCabinet.setPc(powerdata.getPc());
                                                incomingCabinet.setProjectName(deviceByDeviceName.getNavId());
                                                incomingCabinet.setPowerRoomId(deviceByDeviceName.getPowerRoomId());
                                                incomingCabinet.setPowerRoomName(deviceByDeviceName.getPowerRoomName());
                                                incomingCabinet.setAreaId(deviceByDeviceName.getAreaId());
                                                incomingCabinet.setAreaName(deviceByDeviceName.getAreaName());
                                                int i=incomingCabinetMapper.addIncomingCabinet(incomingCabinet);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
               }
                for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
                    key = entry.getKey();
                    Device deviceByDeviceName=null;
                    if(key.substring(0,2).equals("通道")){
                        int i = key.indexOf("_");
                        if(i!= -1){
                            String str = key.substring(i + 1);
                            deviceByDeviceName = deviceMapper.getAllDeviceByDeviceName(str);
                        }
                    }else{
                        deviceByDeviceName = deviceMapper.getAllDeviceByDeviceName(key);
                    }
                    if(deviceByDeviceName!=null){
                        String jsonStr = dataJson.getString(key);
                        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                        if (jsonArray != null) {
                            if (jsonArray.size()>=28){
                                if(jsonArray.getJSONObject(26).getFloat("quality")==1){
                                    Powerdata powerdata = new Powerdata();
                                    powerdata.setDeviceid(deviceByDeviceName.getSerialNumber());
                                    powerdata.setCreatetime(time);
                                    powerdata.setUa(jsonArray.getJSONObject(0).getFloat("value"));
                                    powerdata.setUb(jsonArray.getJSONObject(1).getFloat("value"));
                                    powerdata.setUc(jsonArray.getJSONObject(2).getFloat("value"));
                                    powerdata.setUab(jsonArray.getJSONObject(3).getFloat("value"));
                                    powerdata.setUbc(jsonArray.getJSONObject(4).getFloat("value"));
                                    powerdata.setUca(jsonArray.getJSONObject(5).getFloat("value"));
                                    powerdata.setIa(jsonArray.getJSONObject(6).getFloat("value"));
                                    powerdata.setIb(jsonArray.getJSONObject(7).getFloat("value"));
                                    powerdata.setIc(jsonArray.getJSONObject(8).getFloat("value"));
                                    powerdata.setPa(jsonArray.getJSONObject(9).getFloat("value"));
                                    powerdata.setPb(jsonArray.getJSONObject(10).getFloat("value"));
                                    powerdata.setPc(jsonArray.getJSONObject(11).getFloat("value"));
                                    powerdata.setPt(jsonArray.getJSONObject(12).getFloat("value"));
                                    powerdata.setPan(jsonArray.getJSONObject(13).getFloat("value"));
                                    powerdata.setPbn(jsonArray.getJSONObject(14).getFloat("value"));
                                    powerdata.setPcn(jsonArray.getJSONObject(15).getFloat("value"));
                                    powerdata.setPtn(jsonArray.getJSONObject(16).getFloat("value"));
                                    powerdata.setPain(jsonArray.getJSONObject(17).getFloat("value"));
                                    powerdata.setPbin(jsonArray.getJSONObject(18).getFloat("value"));
                                    powerdata.setPcin(jsonArray.getJSONObject(19).getFloat("value"));
                                    powerdata.setPtin(jsonArray.getJSONObject(20).getFloat("value"));
                                    powerdata.setPaf(jsonArray.getJSONObject(21).getFloat("value"));
                                    powerdata.setPbf(jsonArray.getJSONObject(22).getFloat("value"));
                                    powerdata.setPcf(jsonArray.getJSONObject(23).getFloat("value"));
                                    powerdata.setPtf(jsonArray.getJSONObject(24).getFloat("value"));
                                    powerdata.setFrequency(jsonArray.getJSONObject(25).getFloat("value"));
                                    powerdata.setWpp(jsonArray.getJSONObject(26).getFloat("value"));
                                    powerdata.setEpp(jsonArray.getJSONObject(27).getFloat("value"));
                                    powerdata.setMwpp(jsonArray.getJSONObject(28).getFloat("value"));
                                    powerdata.setForwardActiveTotalElectricalEnergy(jsonArray.getJSONObject(26).getFloat("value"));
                                    powerdata.setDeviceName(deviceByDeviceName.getDeviceName());
                                    redisTemplate.opsForValue().set(powerdata.getDeviceid(),powerdata,12,TimeUnit.SECONDS);
                                }
                            }
                        }
                    }
                }
            } else if (type.equals("alarm")) {
                String list = jsonObject.getString("list");
                JSONArray jsonArray = JSONArray.parseArray(list);
                for(int i=0;i<jsonArray.size();i++){
                    Integer t = jsonArray.getJSONObject(i).getInteger("t");
                    if(t!=0) {
                        String deviceName = jsonArray.getJSONObject(i).getString("dev_name");
                        String m = jsonArray.getJSONObject(i).getString("m");
                        Integer faultTypes = null;
                        if (m.contains("通讯中断")) {
                            faultTypes = 4;
                        } else {
                            faultTypes = 1;
                        }
                        Device device = deviceMapper.getAllDeviceByDeviceName(deviceName);
                        if (device != null) {
                          List<Marketing> marketings = marketingMapper.queryMarketingByprojectId(device.getProjectId());
                          OrderDelivery orderDelivery = new OrderDelivery();
                            orderDelivery.setOrderDeliveryId(IdUtil.getRandomString(8));
                            orderDelivery.setOrderTypes(1);
                            orderDelivery.setRank(1);
                            orderDelivery.setFault(m);
                            orderDelivery.setFaultTime(new Date());
                            orderDelivery.setFaultTypes(faultTypes);
                            orderDelivery.setOrderStatus(1);
                            orderDelivery.setFlag(1);
                            orderDelivery.setAreaId(device.getAreaId());
                            orderDelivery.setAreaName(device.getAreaName());
                            orderDelivery.setProjectId(device.getProjectId());
                            orderDelivery.setProjectName(device.getNavId());
                            orderDelivery.setRoomId(device.getPowerRoomId());
                            orderDelivery.setRoomName(device.getPowerRoomName());
                            orderDelivery.setDeviceId(device.getDeviceId());
                            orderDelivery.setDeviceName(device.getDeviceName());
                            orderDelivery.setDeviceAddress(device.getDeviceAddress());
                            orderDelivery.setSn(device.getSerialNumber());
                            int insert = orderDeliveryMapper.insert(orderDelivery);
                            //推送
                            List<String> clientIdList = pushMapper.getClientId(orderDelivery.getProjectId());
                            PushUtils.sendMessage(clientIdList,orderDelivery.getRoomName(),orderDelivery.getDeviceName(),orderDelivery.getFault());
                            //创建工单
                            WorkOrder workOrder=new WorkOrder();
                            workOrder.setOrderDeliveryId(orderDelivery.getOrderDeliveryId());
                            workOrder.setOrderTypes(1);
                            workOrder.setRank(1);
                            workOrder.setFault(m);
                            workOrder.setFaultTime(new Date());
                            workOrder.setFaultTypes(faultTypes);
                            workOrder.setOrderStatus(1);
                            workOrder.setFlag(1);
                            workOrder.setAreaId(device.getAreaId());
                            workOrder.setAreaName(device.getAreaName());
                            workOrder.setProjectId(device.getProjectId());
                            workOrder.setProjectName(device.getNavId());
                            workOrder.setRoomId(device.getPowerRoomId());
                            workOrder.setRoomName(device.getPowerRoomName());
                            workOrder.setDeviceId(device.getDeviceId());
                            workOrder.setDeviceName(device.getDeviceName());
                            workOrder.setDeviceAddress(device.getDeviceAddress());
                            workOrder.setSn(device.getSerialNumber());
                            workOrder.setAffirmStatus(2);
                            int id=workOrderMapper.addWorkOrder(workOrder);
                            //自动派单
                            WorkOrder  workOrderByProjectId = workOrderMapper.getMaintainerIdWorkOrderByProjectId(device.getProjectId());
                          for (Marketing marketing : marketings) {
                            if(marketing.getStatus() == 1){
                              Maintainer maintainer = maintainerMapper.selectById1(marketing.getMaintainerId());
                              workOrder.setMaintainerId(Integer.parseInt(maintainer.getMaintainerId()));
                              workOrder.setMaintainerName(maintainer.getName());
                              workOrder.setPhone(maintainer.getPhone());
                              workOrder.setDealBeginTime(new Date());
                              workOrder.setOrderDeliveryTime(new Date());
                              workOrder.setOrderStatus(2);
                              workOrderMapper.updateWorkOrderById(workOrder);
                            }
                            //发送短信
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("projectName", workOrder.getProjectName());
                            map.put("powerRoomName", workOrder.getRoomName());
                            map.put("deviceName", workOrder.getDeviceName());
                            map.put("fault", workOrder.getFault());
                            String data = JSONObject.toJSONString(map);
                            SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                          }
                          orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
*//*                            if (workOrderByProjectId==null){
                                Map<Double, String> distanceMap = new HashMap<>();
                                List<Double> distanceList = new ArrayList<>();
                                Project project = projectMapper.queryProjectByProId(device.getProjectId());
                                if (WebSocketServiceImpl.locationMap.size() > 0) {
                                    for (Map.Entry<String, String> entry : WebSocketServiceImpl.locationMap.entrySet()) {
                                        Double distance = CalculateDistanceUtils.getDistance(entry.getValue(), project.getLongitudeLatitude() + "," + project.getLatitude_latitude(), Ellipsoid.Sphere);
                                        distanceMap.put(distance, entry.getKey());
                                        distanceList.add(distance);
                                    }
                                    Collections.sort(distanceList);
                                    for (Double distance : distanceList) {
                                        String maintainerId = distanceMap.get(distance);
                                        List<WorkOrder> orderList = workOrderMapper.getBeingProcessedOrderByMaintainerId(null, null, maintainerId);
                                        if (orderList.size() > 0) {
                                            if (orderDelivery.getProjectId().equals(orderList.get(0).getProjectId())) {
                                                workOrder.setMaintainerId(orderList.get(0).getMaintainerId());
                                                workOrder.setMaintainerName(orderList.get(0).getMaintainerName());
                                                workOrder.setPhone(orderList.get(0).getPhone());
                                                workOrder.setDealBeginTime(new Date());
                                                workOrder.setOrderDeliveryTime(new Date());
                                                workOrder.setOrderStatus(2);
                                              for (Marketing marketing : marketings) {
                                                //发送短信
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("projectName", workOrder.getProjectName());
                                                map.put("powerRoomName", workOrder.getRoomName());
                                                map.put("deviceName", workOrder.getDeviceName());
                                                map.put("fault", workOrder.getFault());
                                                String data = JSONObject.toJSONString(map);
                                                SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                                              }
                                                workOrderMapper.updateWorkOrderById(workOrder);
                                                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                                                break;
                                            }
                                        } else {
                                            Maintainer maintainer = maintainerMapper.selectById1(maintainerId);
                                            //创建工单
                                            workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
                                            workOrder.setMaintainerName(maintainer.getName());
                                            workOrder.setPhone(maintainer.getPhone());
                                            workOrder.setDealBeginTime(new Date());
                                            workOrder.setOrderDeliveryTime(new Date());
                                            workOrder.setOrderStatus(2);
                                          for (Marketing marketing : marketings) {
                                            //发送短信
                                            Map<String, String> map = new HashMap<String, String>();
                                            map.put("projectName", workOrder.getProjectName());
                                            map.put("powerRoomName", workOrder.getRoomName());
                                            map.put("deviceName", workOrder.getDeviceName());
                                            map.put("fault", workOrder.getFault());
                                            String data = JSONObject.toJSONString(map);
                                            SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                                          }
                                            workOrderMapper.updateWorkOrderById(workOrder);
                                            orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                                            break;
                                        }
                                    }
                                }else{
                                    List<Maintainer> MaintainerList = maintainerMapper.getAll();
                                    int flag=0;
                                    for (Maintainer maintainer:MaintainerList){
                                        if(maintainer.getMaintainerId()!=null){
                                            WorkOrder workOrderByMaintainerId = workOrderMapper.getWorkOrderByMaintainerId(maintainer.getMaintainerId());
                                            if(workOrderByMaintainerId==null){
                                                workOrder.setMaintainerId(Integer.valueOf(maintainer.getMaintainerId()));
                                                workOrder.setMaintainerName(maintainer.getName());
                                                workOrder.setPhone(maintainer.getPhone());
                                                workOrder.setDealBeginTime(new Date());
                                                workOrder.setOrderDeliveryTime(new Date());
                                                workOrder.setOrderStatus(2);
                                                workOrderMapper.updateWorkOrderById(workOrder);
                                                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                                              for (Marketing marketing : marketings) {
                                                //发送短信
                                                Map<String, String> map = new HashMap<String, String>();
                                                map.put("projectName", workOrder.getProjectName());
                                                map.put("powerRoomName", workOrder.getRoomName());
                                                map.put("deviceName", workOrder.getDeviceName());
                                                map.put("fault", workOrder.getFault());
                                                String data = JSONObject.toJSONString(map);
                                                SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                                              }
                                                flag=1;
                                                break;
                                            }
                                        }
                                    }
                                    if (flag==0){
                                        workOrder.setMaintainerId(94770617);
                                        workOrder.setMaintainerName("张志光");
                                        workOrder.setPhone("15713878160");
                                        workOrder.setDealBeginTime(new Date());
                                        workOrder.setOrderDeliveryTime(new Date());
                                        workOrder.setOrderStatus(2);
                                        workOrderMapper.updateWorkOrderById(workOrder);
                                        orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));
                                      for (Marketing marketing : marketings) {
                                        //发送短信
                                        Map<String, String> map = new HashMap<String, String>();
                                        map.put("projectName", workOrder.getProjectName());
                                        map.put("powerRoomName", workOrder.getRoomName());
                                        map.put("deviceName", workOrder.getDeviceName());
                                        map.put("fault", workOrder.getFault());
                                        String data = JSONObject.toJSONString(map);
                                        SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                                      }
                                    }
                                }
                            }else{
                                //创建工单
                                workOrder.setMaintainerId(workOrderByProjectId.getMaintainerId());
                                workOrder.setMaintainerName(workOrderByProjectId.getMaintainerName());
                                workOrder.setPhone(workOrderByProjectId.getPhone());
                                workOrder.setDealBeginTime(new Date());
                                workOrder.setOrderDeliveryTime(new Date());
                                workOrder.setOrderStatus(2);
                              for (Marketing marketing : marketings) {
                                //发送短信
                                Map<String, String> map = new HashMap<String, String>();
                                map.put("projectName", workOrder.getProjectName());
                                map.put("powerRoomName", workOrder.getRoomName());
                                map.put("deviceName", workOrder.getDeviceName());
                                map.put("fault", workOrder.getFault());
                                String data = JSONObject.toJSONString(map);
                                SmsUtils.sendSms(marketing.getPhone(),"合一电力","SMS_196616561",data);
                              }
                                workOrderMapper.updateWorkOrderById(workOrder);
                                orderDeliveryMapper.updateOrderStatusById(3,null,null,null,workOrder.getDealBeginTime(),Integer.valueOf(workOrder.getOrderDeliveryId()));

                            }*//*

                        }
                    }
                }

            }

        }
                return 0;
    }*/
}
